import {commonParamChange, getCommonParamInfo, getCommonParamObj, sleep} from "@/utils/commonParamUtil";
import {setJsonValue} from "@/utils/tagCreate";
import request from "@/utils/request";
import jsonpath from "jsonpath";
import router from '../../router'
import { useRoute } from 'vue-router';
import {doThirdExecInfo} from "@/request/lowcode/index";

export function doSubmitVariable(submitAction, awaitObj, commonParam, execThen, execCatch, execParam) {
    // 获取字段名称
    let paramName = submitAction.variableParamName;
    // 获取要设置的值
    let value = submitAction.variableValue;
    commonParamChange(commonParam, paramName, value);
    awaitObj.flag = false;
    execThen(execParam)
}

export async function doSubmitRouteTo(submitAction, awaitObj, commonParam, execThen, execCatch, execParam) {
    // 构建入参
    let buildParam = await getBuildParam(submitAction, commonParam);
    let routeObj = {
        path: submitAction.routeTo,
        query: buildParam
    }
    // 路由
    router.replace(routeObj).then(r => {});
    awaitObj.flag = false;
    execThen(execParam)
}

export async function doSubmitWindowRouteTo(submitAction, awaitObj, commonParam, execThen, execCatch, execParam) {
    // 构建入参
    let buildParam = await getBuildParam(submitAction, commonParam);
    // 构建url
    let path = submitAction.windowRouteTo
    let paramStr = ""
    for (let paramName in buildParam) {
        let paramValue = buildParam[paramName]
        paramStr += paramName + "=" + paramValue + "&"
    }
    if (paramStr.length > 0) {
        path += "?" + paramStr
    }
    // 跳转
    window.open(path, `_blank`);
    awaitObj.flag = false;
    execThen(execParam)
}

export async function doSubmitApi(submitAction, awaitObj, commonParam, execThen, execCatch, execParam) {
    // 构建入参
    let buildParam = await getBuildParam(submitAction, commonParam);
    // 根据api类型调用方法
    if (submitAction.apiType === "MSSA") {
        doMSSA(buildParam, awaitObj, submitAction, commonParam, execThen, execCatch, execParam)
    } else if (submitAction.apiType === "MSOA") {
        doMSOA(buildParam, awaitObj, submitAction, commonParam, execThen, execCatch, execParam)
    } else if (submitAction.apiType === "RTSA") {
        doRTSA(buildParam, awaitObj, submitAction, commonParam, execThen, execCatch, execParam)
    } else {
        awaitObj.flag = false
    }
}

export function doMSSA(requestParam, awaitObj, submitAction, commonParam, execThen, execCatch, execParam) {
    // 处理微服务共享API
}

export function doMSOA(requestParam, awaitObj, submitAction, commonParam, execThen, execCatch, execParam) {
    // 处理微服务自有API
    let methodType = "";
    if (submitAction.apiMethod === 'GET') {
        methodType = "get";
    } else if (submitAction.apiMethod === 'POST') {
        methodType = "post";
    }
    request({
        url: submitAction.apiPath,
        method: methodType,
        data: requestParam
    }).then(async res => {
        if (submitAction.isAddAfterThirdExec) {
            // 构建三方服务入参
            let execParamInfo = []
            let execParamInfoJson = submitAction.afterExecParamJson
            for (let index = 0; index < execParamInfoJson.length; index++) {
                let info = execParamInfoJson[index]
                let tempParam = {
                    name: info.name,
                    type: info.type,
                    isArray: info.isArray,
                    value: ""
                }
                if (info.execParamInfo.selectType === 'custom') {
                    if (info.execParamInfo.customContent.startsWith("$")) {
                        let jsonRes = jsonpath.query(res, info.execParamInfo.customContent);
                        tempParam.value = JSON.stringify(jsonRes)
                    } else {
                        tempParam.value = info.execParamInfo.customContent
                    }
                } else {
                    // 获取参数内容
                    let resParamInfo = getCommonParamInfo(commonParam, info.execParamInfo.variableName)
                    if (typeof resParamInfo !== "string") {
                        tempParam.value = JSON.stringify(resParamInfo)
                    } else {
                        tempParam.value = resParamInfo
                    }
                }
                execParamInfo.push(tempParam)
            }
            // 执行三方服务
            let resParamInfo = ""
            execParamInfo.push({
                isArray: false,
                name: "responseData",
                type: "string",
                value: JSON.stringify(res)
            })
            let doThirdExecParam = {
                code: submitAction.afterThirdExecCode,
                execParam: execParamInfo
            }
            await doThirdExecInfo(doThirdExecParam).then(res => {
                let data = res.data;
                try {
                    resParamInfo = JSON.parse(data)
                } catch (err) {
                    console.log("json parse error, use default value!!")
                    resParamInfo = data
                }
            })
            res = resParamInfo;
        }
        // 解析返回结果
        let responseInfoList = submitAction.apiResponseList;
        if (!responseInfoList) {
            awaitObj.flag = false
            execThen(execParam)
            return
        }
        for (let i = 0; i < responseInfoList.length; i++) {
            let response = responseInfoList[i]
            // 从返回的结果中解析值
            let jsonPath = response.variableValue
            let commonParamObj = getCommonParamObj(commonParam, response.variableName)
            let resValue = ""
            if (commonParamObj.variableType === "Array") {
                resValue = jsonpath.query(res, jsonPath)
            } else if (commonParamObj.variableType === "String") {
                let temp = jsonpath.query(res, jsonPath)[0]
                if (typeof temp === "string") {
                    resValue = temp;
                } else {
                    resValue = JSON.stringify(temp);
                }
            } else {
                resValue = jsonpath.query(res, jsonPath)[0]
            }
            commonParamObj.variableValue = resValue
        }
        awaitObj.flag = false
        awaitObj.res = true
        execThen(execParam)
    }).catch(res => {
        awaitObj.flag = false
        awaitObj.res = false
        execCatch(execParam)
    })
}

export function doRTSA(requestParam, awaitObj, submitAction, commonParam, execThen, execCatch, execParam) {
    // 处理通用透传API
}

export async function doThirdServiceAction(actionList, awaitObj, commonParam, execThen, execCatch, execParam) {
    // 是否异步执行
    if (actionList.length === 0) {
        return
    }
    let isAsyncAction = actionList[0].isAsyncAction;
    if (!isAsyncAction) {
        isAsyncAction = false;
    }
    // 遍历所有的取消动作
    for (let i = 0; i < actionList.length; i++) {
        let submitAction = actionList[i];
        // 根据不同的类型进行不同的处理
        let type = submitAction.type;
        while (awaitObj.flag) {
            if (isAsyncAction) {
                break
            }
            await sleep(1)
        }
        if (type === "api") {
            awaitObj.flag = true
            doSubmitApi(submitAction, awaitObj, commonParam, execThen, execCatch, execParam);
        } else if (type === "variable") {
            awaitObj.flag = true
            doSubmitVariable(submitAction, awaitObj, commonParam, execThen, execCatch, execParam)
        } else if (type === "route") {
            awaitObj.flag = true
            doSubmitRouteTo(submitAction, awaitObj, commonParam, execThen, execCatch, execParam)
        } else if (type === "windowRoute") {
            awaitObj.flag = true
            doSubmitWindowRouteTo(submitAction, awaitObj, commonParam, execThen, execCatch, execParam)
        }
        if (!awaitObj.res) {
            return
        }
    }
}

export async function doThirdServiceValue(actionInfo, commonParam, execThen, execCatch, execParam) {
    if (actionInfo.optionValueType === "custom") {
        doValueCustom(actionInfo, commonParam, execThen, execCatch, execParam);
    } else if (actionInfo.optionValueType === "variable") {
        doValueVariable(actionInfo, commonParam, execThen, execCatch, execParam);
    } else if (actionInfo.optionValueType === "api") {
        await doValueApi(actionInfo, commonParam, execThen, execCatch, execParam);
    } else if (actionInfo.optionValueType === "dataDict") {
        await doValueDataDict(actionInfo, commonParam, execThen, execCatch, execParam);
    }
}

export function doValueCustom(actionInfo, commonParam, execThen, execCatch, execParam) {
    let option = actionInfo.optionsCustom
    let list = []
    if (actionInfo.optionsCustomValueType === "String") {
        execThen(option, execParam)
        return;
    }
    if (actionInfo.optionsCustomValueType === "Array") {
        if (Array.isArray(option)) {
            list = option
        } else {
            if (!actionInfo.optionsCustom) {
                execThen(list, execParam)
                return;
            }
            let newStr = actionInfo.optionsCustom.replaceAll("\'", "\"");
            list = JSON.parse(newStr)
        }
        execThen(list, execParam)
        return;
    }
    if (actionInfo.optionsCustomValueType === "Object") {
        if (typeof option === "object") {
            execThen(option, execParam)
            return;
        }
        let newStr = actionInfo.optionsCustom.replaceAll("\'", "\"");
        let resObj = JSON.parse(newStr)
        execThen(resObj, execParam)
    }
}

export function doValueVariable(actionInfo, commonParam, execThen, execCatch, execParam) {
    // 获取绑定字段
    let paramName = actionInfo.optionsVariableParam;
    // 根据字段名称获取值
    let res = getCommonParamInfo(commonParam, paramName)
    execThen(res, execParam)
}

export function doValueDataDict(actionInfo, commonParam, execThen, execCatch, execParam) {
    request({
        url: "/ywu/data/dict/data.dict.query.info",
        method: "post",
        data: {
            name: actionInfo.optionsDataDict
        }
    }).then(async res => {
        res = res.data.value;
        if (actionInfo.isAddAfterThirdExec) {
            // 构建三方服务入参
            let execParamInfo = []
            let execParamInfoJson = actionInfo.afterExecParamJson
            for (let index = 0; index < execParamInfoJson.length; index++) {
                let info = execParamInfoJson[index]
                let tempParam = {
                    value: "",
                    type: info.type,
                    name: info.name,
                    isArray: info.isArray,
                }
                if (info.execParamInfo.selectType === 'custom') {
                    if (!info.execParamInfo.customContent.startsWith("$")) {
                        tempParam.value = info.execParamInfo.customContent
                    } else {
                        let jsonRes = jsonpath.query(dataDictValue, info.execParamInfo.customContent);
                        tempParam.value = JSON.stringify(jsonRes)
                    }
                } else {
                    // 获取参数内容
                    let resParamInfo = getCommonParamInfo(commonParam, info.execParamInfo.variableName)
                    if (typeof resParamInfo === "string") {
                        tempParam.value = resParamInfo
                    } else {
                        tempParam.value = JSON.stringify(resParamInfo)
                    }
                }
                execParamInfo.push(tempParam)
            }
            // 执行三方服务
            let resParamInfo = ""
            let doThirdExecParam = {
                execParam: execParamInfo,
                code: actionInfo.afterThirdExecCode
            }
            await doThirdExecInfo(doThirdExecParam).then(res => {
                let data = res.data;
                try {
                    resParamInfo = JSON.parse(data)
                } catch (err) {
                    console.log("json parse error, use default value!!")
                    resParamInfo = data
                }
            })
            res = resParamInfo;
        }
        // 解析返回结果
        let responseInfo = actionInfo.apiResponseJsonPath;
        if (responseInfo) {
            let responseList = jsonpath.query(res, responseInfo)
            execThen(responseList[0], execParam)
        } else {
            execThen(res, execParam)
        }
    }).catch(res => {
        execCatch()
    })
}

export async function getBuildParam(actionInfo, commonParam) {
    let res = {};
    // 如果配置的前置服务，则调用三方服务接口，将返回值转换为Json并返回
    if (actionInfo.isAddBeforeThirdExec) {
        res =  await doThirdExec(actionInfo, commonParam)
    } else {
        res =  await doParamCommon(actionInfo, commonParam);
    }
    return res;
}

export async function doThirdExec(actionInfo, commonParam) {
    // 构建三方服务入参
    let execParamInfo = []
    let execParamInfoJson = actionInfo.beforeExecParamJson
    for (let index = 0; index < execParamInfoJson.length; index++) {
        let info = execParamInfoJson[index]
        let tempParam = {
            name: info.name,
            type: info.type,
            isArray: info.isArray,
            value: ""
        }
        if (info.execParamInfo.selectType === 'custom') {
            tempParam.value = info.execParamInfo.customContent
        } else {
            // 获取参数内容
            let resParamInfo = getCommonParamInfo(commonParam, info.execParamInfo.variableName)
            if (typeof resParamInfo !== "string") {
                tempParam.value = JSON.stringify(resParamInfo)
            } else {
                tempParam.value = resParamInfo
            }
        }
        execParamInfo.push(tempParam)
    }
    // 执行三方服务
    let resParamInfo = ""
    let doThirdExecParam = {
        code: actionInfo.beforeThirdExecCode,
        execParam: execParamInfo
    }
    await doThirdExecInfo(doThirdExecParam).then(res => {
        let data = res.data;
        try {
            resParamInfo = JSON.parse(data)
        } catch (err) {
            console.log("json parse error, use default value!!")
            resParamInfo = data
        }
    })
    return resParamInfo ? resParamInfo : {};
}

export async function doParamCommon(actionInfo, commonParam) {
    let buildParam = {}
    let params = actionInfo.apiParamList
    if (!params) {
        return buildParam;
    }
    for (let i = 0; i < params.length; i++) {
        let requestParam = params[i]
        if (requestParam.type === "custom") {
            let resValue = ""
            if (requestParam.variableType === "String") {
                resValue = requestParam.variableValue
            } else {
                let newStr = requestParam.variableValue.replaceAll("\'", "\"");
                resValue = JSON.parse(newStr)
            }
            if (requestParam.variableName.startsWith("$.")) {
                setJsonValue(buildParam, requestParam.variableName, resValue)
            } else {
                buildParam[requestParam.variableName] = resValue
            }
        } else if (requestParam.type === "urlQuery") {
            let urlQueryParams = router.currentRoute.value.query
            let resValue = urlQueryParams[requestParam.variableValue]
            // 获取url地址参数信息
            if (requestParam.variableName.startsWith("$.")) {
                setJsonValue(buildParam, requestParam.variableName, resValue)
            } else {
                buildParam[requestParam.variableName] = resValue
            }
        } else {
            let resValue = getCommonParamInfo(commonParam, requestParam.variableParamName)
            if (requestParam.variableName.startsWith("$.")) {
                setJsonValue(buildParam, requestParam.variableName, resValue)
            } else {
                buildParam[requestParam.variableName] = resValue
            }
        }
    }
    return buildParam;
}

export async function doValueApi(actionInfo, commonParam, execThen, execCatch, execParam) {
    // 服务调用
    // 构建入参
    let buildParam = await getBuildParam(actionInfo, commonParam);
    if (actionInfo.apiType === "MSSA") {
        await doValueMSSA(buildParam, commonParam, actionInfo, execThen, execCatch, execParam)
    } else if (actionInfo.apiType === "MSOA") {
        await doValueMSOA(buildParam, commonParam, actionInfo, execThen, execCatch, execParam)
    } else if (actionInfo.apiType === "RTSA") {
        await doValueRTSA(buildParam, commonParam, actionInfo, execThen, execCatch, execParam)
    }
}

export async function doValueMSSA(requestParam, commonParam, actionInfo, execThen, execCatch, execParam) {

}

export async function doValueMSOA(requestParam, commonParam, actionInfo, execThen, execCatch, execParam) {
    // 处理微服务自有API
    let methodType = "";
    if (actionInfo.apiMethod === 'GET') {
        methodType = "get";
    } else if (actionInfo.apiMethod === 'POST') {
        methodType = "post";
    }
    request({
        url: actionInfo.apiPath,
        method: methodType,
        data: requestParam
    }).then(async res => {
        if (actionInfo.isAddAfterThirdExec) {
            // 构建三方服务入参
            let execParamInfo = []
            let execParamInfoJson = actionInfo.afterExecParamJson
            for (let index = 0; index < execParamInfoJson.length; index++) {
                let info = execParamInfoJson[index]
                let tempParam = {
                    type: info.type,
                    name: info.name,
                    isArray: info.isArray,
                    value: ""
                }
                if (info.execParamInfo.selectType === 'custom') {
                    if (!info.execParamInfo.customContent.startsWith("$")) {
                        tempParam.value = info.execParamInfo.customContent
                    } else {
                        let jsonRes = jsonpath.query(res, info.execParamInfo.customContent);
                        tempParam.value = JSON.stringify(jsonRes)
                    }
                } else {
                    // 获取参数内容
                    let resParamInfo = getCommonParamInfo(commonParam, info.execParamInfo.variableName)
                    if (typeof resParamInfo !== "string") {
                        tempParam.value = JSON.stringify(resParamInfo)
                    } else {
                        tempParam.value = resParamInfo
                    }
                }
                execParamInfo.push(tempParam)
            }
            // 执行三方服务
            let resParamInfo = ""
            let doThirdExecParam = {
                code: actionInfo.afterThirdExecCode,
                execParam: execParamInfo
            }
            await doThirdExecInfo(doThirdExecParam).then(res => {
                let data = res.data;
                try {
                    resParamInfo = JSON.parse(data)
                } catch (err) {
                    console.log("json parse error, use default value!!")
                    resParamInfo = data
                }
            })
            res = resParamInfo;
        }
        // 解析返回结果
        let responseInfo = actionInfo.apiResponseJsonPath;
        let responseList = jsonpath.query(res, responseInfo)
        execThen(responseList[0], execParam)
    }).catch(res => {
        execCatch()
    })
}

export async function doValueRTSA(requestParam, commonParam, actionInfo, execThen, execCatch, execParam) {

}

/**
 * 分段上传组件使用
 * @param actionInfo
 * @param commonParam
 * @param execThen
 * @param execCatch
 * @param execParam
 * @param customBuildParam
 * @param customBuildParamFlag
 * @returns {Promise<void>}
 */
export async function doUploadApi(actionInfo, commonParam, execThen, execCatch, execParam, customBuildParam, customBuildParamFlag) {
    // 构建入参
    let buildParam;
    if (customBuildParamFlag) {
        buildParam = customBuildParam
    } else {
        buildParam = await getBuildParam(actionInfo, commonParam);
    }
    if (actionInfo.apiType === "MSSA") {
        return await doUploadMSSA(buildParam, commonParam, actionInfo, execThen, execCatch, execParam)
    } else if (actionInfo.apiType === "MSOA") {
        return await doUploadMSOA(buildParam, commonParam, actionInfo, execThen, execCatch, execParam)
    } else if (actionInfo.apiType === "RTSA") {
        return await doUploadRTSA(buildParam, commonParam, actionInfo, execThen, execCatch, execParam)
    }
}

export async function doUploadMSSA(requestParam, commonParam, actionInfo, execThen, execCatch, execParam) {

}

export async function doUploadMSOA(requestParam, commonParam, actionInfo, execThen, execCatch, execParam) {
    // 处理微服务自有API
    let methodType = "";
    if (actionInfo.apiMethod === 'GET') {
        methodType = "get";
    } else if (actionInfo.apiMethod === 'POST') {
        methodType = "post";
    }
    let execRes = {};
    await request({
        url: actionInfo.apiPath,
        method: methodType,
        data: requestParam
    }).then(res => {
        // 解析返回结果
        let responseInfoList = actionInfo.apiResponseList;
        if (!responseInfoList) {
            return execRes
        }
        for (let i = 0; i < responseInfoList.length; i++) {
            let response = responseInfoList[i]
            // 从返回的结果中解析值
            let jsonPath = response.variableValue
            execRes[response.variableName] = jsonpath.query(res, jsonPath)[0];
        }
        execThen();
    }).catch(error => {
        execCatch(error);
        throw new Error(error);
    })
    return execRes;
}

export async function doUploadRTSA(requestParam, commonParam, actionInfo, execThen, execCatch, execParam) {

}